package net.jgrm.common.util;

import cn.hutool.core.util.StrUtil;

import java.util.Date;

/**
 * 用户信息业务处理示例
 * 展示在实际业务中如何使用数据脱敏和加密
 *
 * @author service-common
 * @since 1.0-SNAPSHOT
 */
public class UserInfoService {

    /**
     * 用户实体类（数据库存储）
     */
    public static class UserEntity {
        private String userId;
        private String name;
        private String encryptedMobile;    // 加密存储的手机号
        private String encryptedIdCard;    // 加密存储的身份证
        private String encryptedBankCard;  // 加密存储的银行卡
        private String email;
        private String address;
        private Date createTime;
        private Date updateTime;

        // 构造方法
        public UserEntity() {
        }

        public UserEntity(String userId, String name, String mobile, String idCard,
                          String bankCard, String email, String address) {
            this.userId = userId;
            this.name = name;
            this.encryptedMobile = DataMaskingUtil.MobileUtil.encrypt(mobile);
            this.encryptedIdCard = DataMaskingUtil.IdCardUtil.encrypt(idCard);
            this.encryptedBankCard = DataMaskingUtil.BankCardUtil.encrypt(bankCard);
            this.email = email;
            this.address = address;
            this.createTime = new Date();
            this.updateTime = new Date();
        }

        // Getter 和 Setter 方法
        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getEncryptedMobile() {
            return encryptedMobile;
        }

        public void setEncryptedMobile(String encryptedMobile) {
            this.encryptedMobile = encryptedMobile;
        }

        public String getEncryptedIdCard() {
            return encryptedIdCard;
        }

        public void setEncryptedIdCard(String encryptedIdCard) {
            this.encryptedIdCard = encryptedIdCard;
        }

        public String getEncryptedBankCard() {
            return encryptedBankCard;
        }

        public void setEncryptedBankCard(String encryptedBankCard) {
            this.encryptedBankCard = encryptedBankCard;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public Date getCreateTime() {
            return createTime;
        }

        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }

        public Date getUpdateTime() {
            return updateTime;
        }

        public void setUpdateTime(Date updateTime) {
            this.updateTime = updateTime;
        }

        /**
         * 获取解密后的手机号
         */
        public String getMobile() {
            return StrUtil.isNotBlank(encryptedMobile) ?
                    DataMaskingUtil.MobileUtil.decrypt(encryptedMobile) : null;
        }

        /**
         * 获取解密后的身份证
         */
        public String getIdCard() {
            return StrUtil.isNotBlank(encryptedIdCard) ?
                    DataMaskingUtil.IdCardUtil.decrypt(encryptedIdCard) : null;
        }

        /**
         * 获取解密后的银行卡
         */
        public String getBankCard() {
            return StrUtil.isNotBlank(encryptedBankCard) ?
                    DataMaskingUtil.BankCardUtil.decrypt(encryptedBankCard) : null;
        }
    }

    /**
     * 用户VO类（前端显示，脱敏处理）
     */
    public static class UserVO {
        private String userId;
        private String name;
        private String maskedMobile;      // 脱敏显示的手机号
        private String maskedIdCard;      // 脱敏显示的身份证
        private String maskedBankCard;    // 脱敏显示的银行卡
        private String maskedEmail;       // 脱敏显示的邮箱
        private String maskedAddress;     // 脱敏显示的地址
        private String createTimeStr;
        private String updateTimeStr;

        // 从UserEntity创建UserVO（脱敏处理）
        public static UserVO fromEntity(UserEntity entity) {
            UserVO vo = new UserVO();
            vo.userId = entity.getUserId();
            vo.name = DataMaskingUtil.CommonUtil.maskName(entity.getName());
            vo.maskedMobile = DataMaskingUtil.MobileUtil.mask(entity.getMobile());
            vo.maskedIdCard = DataMaskingUtil.IdCardUtil.mask(entity.getIdCard());
            vo.maskedBankCard = DataMaskingUtil.BankCardUtil.mask(entity.getBankCard());
            vo.maskedEmail = DataMaskingUtil.CommonUtil.maskEmail(entity.getEmail());
            vo.maskedAddress = DataMaskingUtil.CommonUtil.maskAddress(entity.getAddress());
            // 日期格式化这里简化处理
            vo.createTimeStr = entity.getCreateTime() != null ? entity.getCreateTime().toString() : null;
            vo.updateTimeStr = entity.getUpdateTime() != null ? entity.getUpdateTime().toString() : null;
            return vo;
        }

        // Getter 和 Setter 方法
        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getMaskedMobile() {
            return maskedMobile;
        }

        public void setMaskedMobile(String maskedMobile) {
            this.maskedMobile = maskedMobile;
        }

        public String getMaskedIdCard() {
            return maskedIdCard;
        }

        public void setMaskedIdCard(String maskedIdCard) {
            this.maskedIdCard = maskedIdCard;
        }

        public String getMaskedBankCard() {
            return maskedBankCard;
        }

        public void setMaskedBankCard(String maskedBankCard) {
            this.maskedBankCard = maskedBankCard;
        }

        public String getMaskedEmail() {
            return maskedEmail;
        }

        public void setMaskedEmail(String maskedEmail) {
            this.maskedEmail = maskedEmail;
        }

        public String getMaskedAddress() {
            return maskedAddress;
        }

        public void setMaskedAddress(String maskedAddress) {
            this.maskedAddress = maskedAddress;
        }

        public String getCreateTimeStr() {
            return createTimeStr;
        }

        public void setCreateTimeStr(String createTimeStr) {
            this.createTimeStr = createTimeStr;
        }

        public String getUpdateTimeStr() {
            return updateTimeStr;
        }

        public void setUpdateTimeStr(String updateTimeStr) {
            this.updateTimeStr = updateTimeStr;
        }
    }

    /**
     * 用户DTO类（接收前端数据）
     */
    public static class UserDTO {
        private String name;
        private String mobile;
        private String idCard;
        private String bankCard;
        private String email;
        private String address;

        // 构造方法
        public UserDTO() {
        }

        public UserDTO(String name, String mobile, String idCard, String bankCard, String email, String address) {
            this.name = name;
            this.mobile = mobile;
            this.idCard = idCard;
            this.bankCard = bankCard;
            this.email = email;
            this.address = address;
        }

        // Getter 和 Setter 方法
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getMobile() {
            return mobile;
        }

        public void setMobile(String mobile) {
            this.mobile = mobile;
        }

        public String getIdCard() {
            return idCard;
        }

        public void setIdCard(String idCard) {
            this.idCard = idCard;
        }

        public String getBankCard() {
            return bankCard;
        }

        public void setBankCard(String bankCard) {
            this.bankCard = bankCard;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }
    }

    /**
     * 用户管理服务类
     */
    public static class UserService {

        /**
         * 创建用户（模拟业务逻辑）
         */
        public UserEntity createUser(UserDTO userDTO) {
            // 1. 数据验证
            validateUserData(userDTO);

            // 2. 生成用户ID
            String userId = "USER_" + System.currentTimeMillis();

            // 3. 创建用户实体（自动加密敏感信息）
            UserEntity userEntity = new UserEntity(
                    userId,
                    userDTO.getName(),
                    userDTO.getMobile(),
                    userDTO.getIdCard(),
                    userDTO.getBankCard(),
                    userDTO.getEmail(),
                    userDTO.getAddress()
            );

            // 4. 这里应该保存到数据库
            // userRepository.save(userEntity);

            System.out.println("用户创建成功，ID: " + userId);
            return userEntity;
        }

        /**
         * 获取用户信息（返回脱敏后的VO）
         */
        public UserVO getUserInfo(String userId) {
            // 1. 从数据库查询用户实体
            UserEntity userEntity = getUserEntityById(userId);

            if (userEntity == null) {
                throw new RuntimeException("用户不存在");
            }

            // 2. 转换为VO（自动脱敏）
            return UserVO.fromEntity(userEntity);
        }

        /**
         * 获取用户完整信息（内部使用，需要权限验证）
         */
        public UserEntity getUserFullInfo(String userId, boolean hasPermission) {
            if (!hasPermission) {
                throw new RuntimeException("无权限访问用户完整信息");
            }

            return getUserEntityById(userId);
        }

        /**
         * 更新用户手机号
         */
        public void updateMobile(String userId, String newMobile) {
            // 1. 验证手机号格式
            if (!cn.hutool.core.lang.Validator.isMobile(newMobile)) {
                throw new RuntimeException("手机号格式不正确");
            }

            // 2. 查询用户
            UserEntity userEntity = getUserEntityById(userId);
            if (userEntity == null) {
                throw new RuntimeException("用户不存在");
            }

            // 3. 更新加密的手机号
            userEntity.setEncryptedMobile(DataMaskingUtil.MobileUtil.encrypt(newMobile));
            userEntity.setUpdateTime(new Date());

            // 4. 保存到数据库
            // userRepository.update(userEntity);

            System.out.println("用户手机号更新成功");
        }

        /**
         * 验证用户手机号（用于登录验证等场景）
         */
        public boolean verifyMobile(String userId, String inputMobile) {
            UserEntity userEntity = getUserEntityById(userId);
            if (userEntity == null) {
                return false;
            }

            // 解密存储的手机号进行比对
            String storedMobile = userEntity.getMobile();
            return inputMobile.equals(storedMobile);
        }

        /**
         * 数据验证
         */
        private void validateUserData(UserDTO userDTO) {
            if (StrUtil.isBlank(userDTO.getName())) {
                throw new RuntimeException("姓名不能为空");
            }

            if (!cn.hutool.core.lang.Validator.isMobile(userDTO.getMobile())) {
                throw new RuntimeException("手机号格式不正确");
            }

            if (!DataMaskingUtil.IdCardUtil.validate(userDTO.getIdCard())) {
                throw new RuntimeException("身份证格式不正确");
            }

            if (!cn.hutool.core.lang.Validator.isEmail(userDTO.getEmail())) {
                throw new RuntimeException("邮箱格式不正确");
            }
        }

        /**
         * 模拟从数据库获取用户实体
         */
        private UserEntity getUserEntityById(String userId) {
            // 这里应该是数据库查询逻辑
            // return userRepository.findById(userId);

            // 模拟返回数据
            if ("USER_123".equals(userId)) {
                UserEntity entity = new UserEntity();
                entity.setUserId(userId);
                entity.setName("张三");
                entity.setEncryptedMobile(DataMaskingUtil.MobileUtil.encrypt("13812345678"));
                entity.setEncryptedIdCard(DataMaskingUtil.IdCardUtil.encrypt("110101199003078515"));
                entity.setEncryptedBankCard(DataMaskingUtil.BankCardUtil.encrypt("6225880123456789"));
                entity.setEmail("zhangsan@example.com");
                entity.setAddress("北京市朝阳区三里屯街道100号");
                entity.setCreateTime(new Date());
                entity.setUpdateTime(new Date());
                return entity;
            }

            return null;
        }
    }

    /**
     * 使用示例
     */
    public static void main(String[] args) {
        System.out.println("=== 用户信息管理服务示例 ===");

        UserService userService = new UserService();

        // 1. 创建用户
        System.out.println("1. 创建用户:");
        UserDTO userDTO = new UserDTO(
                "李四",
                "13987654321",
                "110101199501018888",
                "6225880987654321",
                "lisi@example.com",
                "上海市浦东新区陆家嘴街道200号"
        );

        UserEntity createdUser = userService.createUser(userDTO);
        System.out.println("创建的用户ID: " + createdUser.getUserId());
        System.out.println("加密后的手机号: " + createdUser.getEncryptedMobile());
        System.out.println("解密后的手机号: " + createdUser.getMobile());
        System.out.println();

        // 2. 获取用户信息（脱敏显示）
        System.out.println("2. 获取用户信息（脱敏显示）:");
        UserVO userVO = userService.getUserInfo("USER_123");
        System.out.println("用户ID: " + userVO.getUserId());
        System.out.println("脱敏姓名: " + userVO.getName());
        System.out.println("脱敏手机号: " + userVO.getMaskedMobile());
        System.out.println("脱敏身份证: " + userVO.getMaskedIdCard());
        System.out.println("脱敏银行卡: " + userVO.getMaskedBankCard());
        System.out.println("脱敏邮箱: " + userVO.getMaskedEmail());
        System.out.println();

        // 3. 获取用户完整信息（需要权限）
        System.out.println("3. 获取用户完整信息（需要权限）:");
        try {
            UserEntity fullInfo = userService.getUserFullInfo("USER_123", true);
            System.out.println("完整手机号: " + fullInfo.getMobile());
            System.out.println("完整身份证: " + fullInfo.getIdCard());
            System.out.println("完整银行卡: " + fullInfo.getBankCard());
        } catch (Exception e) {
            System.out.println("获取失败: " + e.getMessage());
        }
        System.out.println();

        // 4. 更新用户手机号
        System.out.println("4. 更新用户手机号:");
        userService.updateMobile("USER_123", "13911111111");
        System.out.println();

        // 5. 验证用户手机号
        System.out.println("5. 验证用户手机号:");
        boolean verified = userService.verifyMobile("USER_123", "13911111111");
        System.out.println("手机号验证结果: " + verified);

        System.out.println("\n=== 示例执行完成 ===");
    }
}